<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <h2>系统登录</h2>
        </div>
      </template>
      
      <el-form
        ref="formRef"
        :model="loginForm"
        :rules="rules"
        label-width="0"
        class="login-form">
        <el-form-item prop="userId">
          <el-input
            v-model="loginForm.userId"
            placeholder="请输入用户ID"
            prefix-icon="User"
            clearable />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
            clearable
            @keyup.enter="handleLogin" />
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            class="login-button"
            @click="handleLogin">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { userLogin } from '@/api/userApi'

const router = useRouter()
const formRef = ref(null)
const loading = ref(false)

const loginForm = reactive({
  userId: '',
  password: ''
})

const rules = {
  userId: [
    { required: true, message: '请输入用户ID', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        console.log('发送登录请求:', loginForm)
        const res = await userLogin(loginForm)
        console.log('登录响应:', res)

        if (res.code === 200 && res.data) {
          // 存储用户信息
          localStorage.setItem('user', JSON.stringify(res.data))
          // 存储token（如果后端返回的话）
          if (res.data.token) {
            localStorage.setItem('token', res.data.token)
          }
          ElMessage.success('登录成功')
          // 跳转到仪表板
          router.push('/dashboard')
        } else {
          console.error('登录失败 - 响应码或数据异常:', res)
          ElMessage.error(res.message || '用户ID或密码错误')
        }
      } catch (error) {
        console.error('登录失败 - 网络或其他错误:', error)
        console.error('错误详情:', error.response || error.message || error)
        ElMessage.error('登录失败，请检查网络连接')
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f7fa;
}

.login-card {
  width: 400px;
  border-radius: 8px;
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.login-form {
  padding: 20px 0;
}

.login-button {
  width: 100%;
}
</style> 